package com.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

/**
 * 阿里云短信发送工具类
 */
public class SendSmsUtil {
    //产品名称:云通信短信API产品,开发者无需替换
    //private static final String PRODUCT = "Dysmsapi";
    //阿里云短信服务产品域名,开发者无需替换
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";
    //阿里云短信服务区域id
    private static final String REGIONID = "cn-hangzhou";
    //阿里云短信服务访问密钥id,此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    private static String ACCESS_KEY_ID = "LTAIEoMJvPI9GA1w";
    //阿里云短信服务访问密钥令牌
    private static String ACCESS_KEY_SECRET = "vOSc4hzkLbdz5HFOrtNKhQLRfjNZY7";
    //短信签名名称
    private static String SIGNNAME = "北漂";
    //模板代码
    private static String TEMPLATECODE = "SMS_78750118";
    //private static String identifyingTempleteCode = "yourAccessKeySecret";

    /**
     * 短信发送
     *
     * @param phone
     * @param validateCode
     * @return
     */
    public static JSONObject sendSms(String phone, String validateCode) {
        JSONObject resData = new JSONObject();
        DefaultProfile profile = DefaultProfile.getProfile(REGIONID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", REGIONID);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", SIGNNAME);
        request.putQueryParameter("TemplateCode", TEMPLATECODE);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + validateCode + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            resData = (JSONObject) JSONObject.parse(response.getData());
            System.out.println(resData);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return resData;
    }

//    public static void main(String[] args) {
//        String phone = "13051222840";
//        String code = "6666";
//        sendSms(phone, code);
//    }
}
